package com.oa.erp.ass.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.audit.log.client.annotation.AuditLog;
import com.mdp.audit.log.client.annotation.OperType;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.erp.ass.entity.AssetCard;
import com.oa.erp.ass.entity.AssetMng;
import com.oa.erp.ass.service.AssetCardOperService;
import com.oa.erp.ass.service.AssetCardService;
import com.oa.erp.ass.service.AssetMngService;
import com.oa.erp.ass.vo.AssetDetailVo;
import com.oa.erp.ass.vo.AssetMngVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/**/oa/erp/ass/assetMng")
@Api(tags = {"资产出租/出借单-操作接口"})
public class AssetMngController {

    static Logger logger = LoggerFactory.getLogger(AssetMngController.class);

    @Autowired
    private AssetMngService assetMngService;

    @Autowired
    private AssetCardService assetCardService;

    @Autowired
    private AssetCardOperService assetCardOperService;

    @ApiOperation(value = "资产出租/出借单-查询列表", notes = " ")
    @ApiEntityParams(AssetMng.class)
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listAssetMng(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        params.put("reqBranchId", user.getBranchId());
        QueryWrapper<AssetMng> qw = QueryTools.initQueryWrapper(AssetMng.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> assetMngList = assetMngService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(assetMngList).setTotal(page.getTotal());
    }


    @ApiOperation(value = "资产出租/出借单-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addAssetMng(@RequestBody AssetMngVo assetMngVo) {
        System.out.println();
        if (StringUtils.isEmpty(assetMngVo.getAssetMng().getId())) {
            assetMngVo.getAssetMng().setId(assetMngService.createKey("id"));
        } else {
            AssetMng assetMngQuery = new AssetMng(assetMngVo.getAssetMng().getId());
            if (assetMngService.countByWhere(assetMngQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        assetMngService.insertAssetMsg(assetMngVo);

        return Result.ok("add-ok", "添加成功！").setData(assetMngVo);
    }

    @ApiOperation(value = "获取单据明细信息", notes = "获取单据明细信息")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/getDetail", method = RequestMethod.GET)
    public Result getDetailById(@RequestParam Map<String, Object> assetMng) {
        Map<String, Object> m = new HashMap<>();
        RequestUtils.transformArray(assetMng, "ids");
        QueryWrapper<AssetMng> qw = QueryTools.initQueryWrapper(AssetMng.class, assetMng);
        IPage page = QueryTools.initPage(assetMng);
        List<Map<String, Object>> assetMngList = assetMngService.getDetailById(page, qw, assetMng);    //列出AssetMng列表

        return Result.ok("query", "查询成功").setData(assetMngList).setTotal(page.getTotal());
    }

    @ApiOperation(value = "资产出租/出借单-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delAssetMng(@RequestBody AssetMng assetMng) {
        assetMngService.deleteMngByPk(assetMng);
//        assetMngService.deleteByWhere(assetMng);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "资产出租/出借单-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editAssetMng(@RequestBody AssetMngVo assetMngVo) {


        assetMngService.updateAssetMsg(assetMngVo);

        return Result.ok("edit-ok", "修改成功！").setData(assetMngVo);
    }

    @ApiOperation(value = "资产出租/出借单-批量修改某些字段", notes = "")
    @ApiEntityParams(value = AssetMng.class, props = {}, remark = "资产出租/出借单", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        assetMngService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "资产出租/出借单-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelAssetMng(@RequestBody List<AssetMng> assetMngs) {
        User user = LoginUtils.getCurrentUserInfo();
        if (assetMngs.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<AssetMng> datasDb = assetMngService.listByIds(assetMngs.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<AssetMng> can = new ArrayList<>();
        List<AssetMng> no = new ArrayList<>();
        for (AssetMng data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            assetMngService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "资产出租/出借单-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(AssetMng assetMng) {
        AssetMng data = (AssetMng) assetMngService.getById(assetMng);
        return Result.ok().setData(data);
    }

    @ApiOperation(value = "新增一条ass_asset_mng信息", notes = "addAssetMng,主键如果为空，后台自动生成")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/addMng", method = RequestMethod.POST)
    public Result addAssetMng2(@RequestBody AssetMngVo assetMngVo) {


        if (StringUtils.isEmpty(assetMngVo.getAssetMng().getId())) {
            assetMngVo.getAssetMng().setId(assetMngService.createKey("id"));
        } else {
            AssetMng assetMngQuery = new AssetMng(assetMngVo.getAssetMng().getId());
            if (assetMngService.countByWhere(assetMngQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        AssetMng assetMng = assetMngVo.getAssetMng();
        List<AssetDetailVo> assetDetailVos = assetMngVo.getAssetDetails();
        Set<String> cardIds = assetDetailVos.stream().map(i -> i.getCardId()).collect(Collectors.toSet());
        List<AssetCard> cardsForFlow = this.assetCardService.selectIsFlowingListByIds(cardIds.stream().collect(Collectors.toList()));
        if (cardsForFlow != null && cardsForFlow.size() > 0) {
            String titles = cardsForFlow.stream().map(i -> i.getAssetName()).collect(Collectors.joining(","));
            return Result.error("card-is-flowing", titles + "正在审核中，不能再申请");

        }
        if ("return".equals(assetMng.getOpType())) {
            //需要检查资产是否已有人申请归还，是否需要归还
            List<AssetCard> cards = this.assetCardService.selectListByIds(cardIds.stream().collect(Collectors.toList()));
            List<AssetCard> cardStatusNotRightList = cards.stream().filter(i -> !"1".equals(i.getCardStatus()) && !"2".equals(i.getCardStatus())).collect(Collectors.toList());
            if (cardStatusNotRightList != null && cardStatusNotRightList.size() > 0) {
                String titles = cardStatusNotRightList.stream().map(i -> i.getAssetName()).collect(Collectors.joining(","));
                return Result.error("cardStatus-not-12", titles + "资产状态不是在用或者租用状态，无需申请归还");
            }

        }
        assetMngService.insertAssetMngOpr(assetMngVo);

        return Result.ok().setData(assetMngVo);
    }

    @ApiOperation(value = "根据主键修改一条ass_asset_mng信息", notes = "editAssetMng")
    @ApiResponses({@ApiResponse(code = 200, response = AssetMng.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editMng", method = RequestMethod.POST)
    public Result editAssetMng2(@RequestBody AssetMngVo assetMngVo) {

        assetMngService.updateAssetMsgOpr(assetMngVo);

        return Result.ok("update-ok", "成功更新一条数据").setData(assetMngVo);
    }

    @AuditLog(firstMenu = "资产管理", secondMenu = "资产领用", func = "processApprova", funcDesc = "资产领用流程", operType = OperType.UPDATE)
    @RequestMapping(value = "/processApprova", method = RequestMethod.POST)
    public Result processApprova(@RequestBody Map<String, Object> flowVars) {


        QueryWrapper<AssetMng> qw = QueryTools.initQueryWrapper(AssetMng.class, flowVars);
        IPage page = QueryTools.initPage(flowVars);

        this.assetMngService.processApprova(page, qw, flowVars);
        logger.debug("procInstId=====" + flowVars.get("procInstId"));

        return Result.ok("submit-ok", "成功提交审批").setTotal(page.getTotal());
    }

    @AuditLog(firstMenu = "资产管理", secondMenu = "资产归还", func = "processApprova", funcDesc = "资产归还流程", operType = OperType.UPDATE)
    @RequestMapping(value = "/returnProcessApprova", method = RequestMethod.POST)
    public Result returnProcessApprova(@RequestBody Map<String, Object> flowVars) {

        QueryWrapper<AssetMng> qw = QueryTools.initQueryWrapper(AssetMng.class, flowVars);
        IPage page = QueryTools.initPage(flowVars);

        this.assetMngService.returnProcessApprova(page, qw, flowVars);
        logger.debug("procInstId=====" + flowVars.get("procInstId"));

        return Result.ok("submit-ok", "成功提交审批").setTotal(page.getTotal());
    }

}
